<template>
  <div class="flex flex-col w-full h-full">
    <n-grid :x-gap="24">
      <n-grid-item span="5">
        <ExtractVoiceConfig :storyId="props.story.id" ref="voiceConfigRef"></ExtractVoiceConfig>
      </n-grid-item>
      <n-grid-item span="19">
        <n-grid x-gap="10">
          <n-grid-item :span="6">
            <n-form-item label="提示词模式选择" path="resourceId">
              <n-select
                  v-model:value="storyCreatorConfig.promptType"
                  :options="promptTypeOptions"
                  :render-label="renderLabel">
              </n-select>
            </n-form-item>
          </n-grid-item>
          <n-grid-item :span="16">
            <n-form  :model="storyCreatorConfig" ref="formRef">
              <n-form-item label="绘画资源选择" path="resourceId">
                <n-select
                    v-model:value="storyCreatorConfig.resourceId"
                    :options="resourceOption"
                    @update:value="resourceSelect"
                    :render-label="renderLabel">
                </n-select>
                <n-tooltip>
                  <template #trigger>
                    <n-button type="primary" @click="loadConfig" style="margin-left:5px; ">刷新
                      <template #icon>
                        <n-icon>
                          <SyncCircleOutline/>
                        </n-icon>
                      </template>
                    </n-button>
                  </template>
                  <span>刷新资源</span>
                </n-tooltip>
              </n-form-item>
            </n-form>
          </n-grid-item>
        </n-grid>

        <Fooocus ref="fooocusText2ImgRef" v-if="selectedResourceOption?.type === 'Fooocus'"></Fooocus>

        <SdText2Img ref="SdText2ImgRef" v-if="selectedResourceOption?.type==='SD'"></SdText2Img>
        <Midjourney ref="midjourneyRef" mode="config" v-if="selectedResourceOption?.type==='MJ'"></Midjourney>
      </n-grid-item>
    </n-grid>
  </div>
</template>

<script setup lang="ts">
import {nextTick, onMounted, reactive, ref} from 'vue';
import {useMessage} from 'naive-ui';
import {resourceController} from '@/api/resource/resourceController.api'
import {storyController} from '@/api/story/story.api'
// @ts-ignore
import fileFunction from "@/libs/globalFunction/file";
import SdText2Img from '@/components/creator/boardConfig/sdtext2Img.vue'
import ExtractVoiceConfig from '@/components/creator/boardConfig/extractVoiceConfig.vue'
import {SyncCircleOutline} from "@vicons/ionicons5";
import Bus from "@/components/file/box/GlobalUploader/utils/bus";
import Midjourney from '@/views/pages/aiart/midjourney/index.vue'
import Fooocus from "@/views/pages/aiart/fooocus/index.vue";

const resourceOption = ref([])
const promptTypeOptions = ref([{
  label: '结构化提示词',
  value: 'easy'
},{
  label: '普通模式',
  value: 'normal'
}])

const selectedResource = ref("")
const selectedResourceOption = ref({
  label: '',
  value: '',
  type: ''
})

const formRef: any = ref(null);
const message = useMessage();

const fooocusText2ImgRef = ref(null)
const voiceConfigRef = ref(null)
const SdText2ImgRef = ref(null)
const midjourneyRef = ref(null)

const storyCreatorConfig: Creator.StoryCreatorConfig = reactive({
  paintType: '',
  resourceId: '',
  chapterId: '',
  voiceType: '',
  paintConfigText: '',
  voiceConfigText: '',
  promptType: ''
})

const props = defineProps({
  story: {
    type: Object,
    default: () => {
      return {}
    }
  }
})

/***
 * 获取绘画资源
 */
const getResourceInfo = async () => {
  try {
    const res = await resourceController.getSDResource('ALL');
    if (res.code === 200) {
      res.data.forEach((item: any) => {
        // @ts-ignore
        resourceOption.value.push({
          label: item.resourceName,
          value: item.id,
          type: item.type,
        });
      });
    } else {
      message.error(res.msg);
    }
  } catch (error) {
    // 处理错误
    console.error(error);
  }
}

/**
 * 获取该章节的绘画配置
 * @param chapterId
 */
const getStoryPaintConfig = async (chapterId: string) => {
  try {
    const res = await storyController.getStoryPaintConfig(chapterId);
    if (res.code === 200) {
      if (res.data != null) {
        Object.assign(storyCreatorConfig, res.data);
        if (storyCreatorConfig.promptType == null || storyCreatorConfig.promptType.length == 0) {
          storyCreatorConfig.promptType = 'easy'
        }
        selectedResourceOption.value.type = res.data.paintType
        selectedResourceOption.value.value = res.data.resourceId
        loadConfig()
      } else {
        if (resourceOption && resourceOption.value.length > 0) {
          storyCreatorConfig.resourceId = resourceOption.value[0].value
          storyCreatorConfig.promptType = 'easy'
          selectedResourceOption.value = resourceOption.value[0]
          loadConfig()
        }
      }
    } else {
      message.error(res.msg);
    }
  } catch (error) {
    console.error(error);
  }
}

const loadConfig = () => {
  nextTick(() => {
    let config = null
    if( storyCreatorConfig.paintConfigText != null && storyCreatorConfig.paintConfigText.length > 0 ){
      config = storyCreatorConfig.paintConfigText
    }
    if(config!=null && config.length > 0){
      // 判断当前选中的资源是否和配置的资源一致
      if(selectedResourceOption.value.type != storyCreatorConfig.paintType || selectedResourceOption.value.value != storyCreatorConfig.resourceId){
        config = null;
      }
    }
    if (selectedResourceOption.value.type == 'Fooocus') {
      fooocusText2ImgRef.value?.loadConfig(config, selectedResourceOption.value.value)
    } else if (selectedResourceOption.value.type == 'SD') {
      SdText2ImgRef.value?.loadConfig(config, selectedResourceOption.value.value)
    }else if (selectedResourceOption.value.type == 'MJ') {
      midjourneyRef.value?.loadConfig(config)
    }
    if (storyCreatorConfig.voiceConfigText != null && storyCreatorConfig.voiceConfigText.length > 0) {
        //加载绘画配置
        voiceConfigRef.value?.loadConfig(storyCreatorConfig.voiceConfigText)
    }
  });
}

// 选中资源后
const resourceSelect = (value: string, option: any) => {
  selectedResource.value = value
  selectedResourceOption.value = option;
  loadConfig()
}


const renderLabel = (option: any) => {
  if (option.type == null || option.type.length == 0) {
    return option.label
  }
  return option.label + ' 【类型:' + option.type + '】'
}


const saveStoryConfig = async (callback: any) => {
  let paintConfig = {}
  if (selectedResourceOption.value.type == 'MJ') {
    paintConfig = await midjourneyRef.value.getConfig()
    // TODO 增加MJ实现
  } else if (selectedResourceOption.value.type == 'Fooocus') {
    paintConfig = await fooocusText2ImgRef.value.getConfig()
  } else if (selectedResourceOption.value.type == 'SD') {
    paintConfig = await SdText2ImgRef.value.getConfig()
  }

  if ( !paintConfig) {
    callback(false)
    return
  }
  storyCreatorConfig.paintType = selectedResourceOption.value.type
  storyCreatorConfig.resourceId = selectedResourceOption.value.value
  storyCreatorConfig.paintConfigText = JSON.stringify(paintConfig)
  storyCreatorConfig.chapterId = props.story.id
  storyController.saveStoryConfig(storyCreatorConfig).then(res => {
    if (res.code === 200) {
      message.success("保存成功")
      Bus.emit('refreshStoryConfig')
      callback(true)
    } else {
      message.error(res.msg);
      callback(false)
    }
  })
}

onMounted(async () => {
  await getResourceInfo()
  await getStoryPaintConfig(props.story.id)
})

defineExpose({
  saveStoryConfig
})
</script>
